import { Form, Table, Input, Button, Pagination, type InputValue, message, DialogProps } from 'tdesign-react';
import React, { useState, useEffect, ChangeEvent } from 'react';
import EmployeeModal from 'components/EmployeeModal';
import ConfirmModal from 'components/ConfirmModal';
import { getEmployeeList, addEmployee, updateEmployee, deleteEmployee } from 'services/employee';
import type { User, UserListRequest, UserListResponse } from 'services/employee';
import 'tdesign-react/es/style/index.css';

const EmployeeManage: React.FC = () => {
  const [employeeList, setEmployeeList] = useState<User[]>([]);
  const [pagination, setPagination] = useState<{
    page: number;
    pageSize: number;
    total: number;
  }>({ page: 1, pageSize: 20, total: 0 });
  const [searchKey, setSearchKey] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false); // 新增弹窗
  const [isEditing, setIsEditing] = useState(false); // 编辑弹窗
  // const [editingEmployee, setEditingEmployee] = useState<User>(); // 编辑数据
  const companyId = '998a5805-ff3d-477d-a598-8348db542ccf';
  const [isDeleting, setIsDeleting] = useState(false); // 删除确认
  const [deletingEmployee, setDeletingEmployee] = useState<User | null>();
  const [editingEmployee, setEditingEmployee] = useState<{
    user_id: string;
    nick_name: string;
    phone?: string;       // [11, 20]
    job_number?: string;  // [1, 20]
    position?: string;
    permissions?: string[];
    registered: boolean,

  } | null>(null);

  const [initialData, setInitialData] = useState<Record<string, any>>({});

  // 获取员工列表
  const fetchEmployeeList = async () => {
    // eslint-disable-next-line no-restricted-globals
    const page = Math.max(1, pagination.page);
    const size = Math.min(100, Math.max(1, pagination.pageSize));
    const params: UserListRequest = {
      company_id: companyId,
      page,
      size,
      search: searchKey || null,
    };

    // console.log('请求参数:', params);

    try {
      const res = await getEmployeeList(params);
      // console.log('后端返回数据:', res.data); // 打印完整响应

      // 修正后应根据实际响应结构调整
      setEmployeeList(res.data.items || []);
      setPagination({ ...pagination, total: res.data.total || 0 });


      // // 关键修复：根据实际数据结构调整
      // const dataArray = Array.isArray(res.data) ? res.data : [];

      // setEmployeeList(dataArray);
      // setPagination({
      //   ...pagination,
      //   total: res.total || dataArray.length // 添加后备值
      // });
    } catch (error) {
      console.error('请求失败:', error);
      setEmployeeList([]);
      setPagination({ ...pagination, total: 0 });
    }
  };

  useEffect(() => {
    console.log('分页状态变更:', pagination);
    // console.log("deletingEmployee 状态变化:", deletingEmployee);
    fetchEmployeeList();
  }, [pagination.page, pagination.pageSize, searchKey, companyId, deletingEmployee]);

  // useEffect(() => {
  //   fetchEmployeeList();
  // }, [pagination.page, pagination.pageSize, searchKey]);



  // 搜索
  const handleSearch = () => {
    setPagination((prev) => ({
      ...prev,
      page: 1,  // 明确使用数字 1
      pageSize: prev.pageSize
    }));
    // 延迟调用确保状态更新
    setTimeout(fetchEmployeeList, 0);
    // setPagination({ ...pagination, page: 1 });
    // fetchEmployeeList();
  };

  // 新增员工
  const handleAdd = () => {
    setIsModalVisible(true); // 显示弹窗
    setIsEditing(false); // 标记为“新增”模式
    setInitialData({}); // 初始化数据为空（新增场景）
  };

  // 编辑员工
  const handleEdit = (employee: User) => {
    setIsModalVisible(true); // 显示弹窗
    setIsEditing(true);
    // setEditingEmployee(employee as { userId: string; nick_name: string } | null);
    setEditingEmployee({
      ...employee,
    });
    //   user_id: employee.user_id,
    //   nick_name: employee.nick_name,
    // } as User); // 强制类型转换
  };


  // 保存员工（新增/编辑）
  const handleSave = async (formData: User) => { // 明确参数类型为 User
    console.log('传递给接口的数据：', formData); // 检查是否包含所有字段

    try {
      await addEmployee(formData);
    } catch (error) {
      // console.error('接口调用错误:', error);
    }
  };



  // 删除确认
  const handleDelete = (rowData: any) => {
    const employee = rowData.row;
    setDeletingEmployee(employee);
    setIsDeleting(true);

  };

  // 确认删除
  const confirmDelete = async () => {
    if (!deletingEmployee || !deletingEmployee.user_id) {
      message.error('未选择要删除的员工');
      return;
    }
    try {
      await deleteEmployee(deletingEmployee.user_id);
      message.success(`已成功删除员工: ${deletingEmployee.nick_name}`);
      await fetchEmployeeList();
    } catch (error) {
      message.error('删除失败，请重试');
    } finally {
      setIsDeleting(false);
      setDeletingEmployee(null);
    }
  };

  const handleChange = (value: InputValue) => {
    setSearchKey(value as string);
  };

  // 表格列配置
  const columns = [
    {
      title: '序号',
      // dataIndex: 'index',
      colKey: 'index',
      // render: (_, __, index: number) => index + 1,
    },
    {
      title: '姓名',
      dataIndex: 'nick_name',
      colKey: 'nick_name',
    },
    { title: '工号', dataIndex: 'job_number', colKey: 'job_number' },
    { title: '岗位', dataIndex: 'position', colKey: 'position' },
    { title: '联系电话', dataIndex: 'phone', colKey: 'phone' },
    { title: '权限', dataIndex: 'permissions', colKey: 'permissions', },
    {
      title: '帐号状态',
      dataIndex: 'registered',
      colKey: 'registered',
    },
    {
      title: '最后操作时间',
      dataIndex: 'updated_at',
      colKey: 'updated_at',
    },

    {
      title: '操作',
      colKey: 'operation',
      width: 150,
      fixed: 'right',
      cell: (row: User) => (
        <>
          <a onClick={() => handleEdit(row)}>修改权限</a>
          <span style={{ margin: '0 8px' }}></span>
          <a onClick={() => handleDelete(row)}>删除</a>
        </>
      ),

    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 搜索 + 新增 */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
        <Input
          placeholder='请输入姓名/工号搜索'
          value={searchKey}
          // onChange={(e) => setSearchKey(e.target.value)} 
          onChange={handleChange}
          onEnter={handleSearch}
        />
        <Button theme='primary' onClick={handleAdd}>
          + 添加员工
        </Button>

      </div>

      {/* 员工列表 */}
      <Table<User>
        data={employeeList || []}
        columns={columns}
        pagination={undefined}// 关闭内置分页，用自定义
        rowKey='job_number'
        stickyHeader
        style={{ width: '100%' }}
      />

      <Pagination
        current={pagination.page}
        pageSize={pagination.pageSize}
        total={pagination.total}
        onChange={(pageInfo) =>
          setPagination({
            ...pagination,
            page: pageInfo.page,
            pageSize: pageInfo.pageSize
          })
        }
        // onChange={(pageInfo) => setPagination({ ...pagination, page: pageInfo.page, pageSize: pageInfo.pageSize })}
        style={{ marginTop: '16px' }}
      />

      {/* 新增/编辑弹窗 */}
      <EmployeeModal
        visible={isModalVisible}
        isEdit={isEditing}
        initialData={editingEmployee}
        onSave={handleSave}
        // onSave={() => {
        //   if (!editingEmployee) return; // 新增场景需确保表单数据完整
        //   handleSave(editingEmployee);
        // }}
        onCancel={() => {
          setIsModalVisible(false);
          setIsEditing(false);
          setEditingEmployee(null);
        }}
      >
        <Form>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <Input
              label='姓名'
              name='nick_name'
              value={editingEmployee?.nick_name || ''}
              onChange={(e) =>
                setEditingEmployee((prev) => ({
                  ...prev!,
                  nick_name: e.target.value
                }))
                // setEditingEmployee({
                //   ...employeeList,
                //   nick_name: e.target.value,
                // })
              }
            />
            <Input
              label='工号'
              name='job_number'
              value={editingEmployee?.job_number || ''}
              onChange={(e) =>
                setEditingEmployee((prev) => ({
                  ...prev!,
                  job_number: e.target.value
                }))
              }
            />
            <Input
              label='联系电话'
              name='phone'
              value={editingEmployee?.phone || ''}
              onChange={(e) => {
                const phone = e.target.value.trim();
                // 简单校验：长度 11 位
                if (phone?.length === 11) {
                  setEditingEmployee((prev) => ({
                    ...prev!,
                    nick_name: e.target.value
                  }));
                } else {
                  message.error('手机号必须为 11 位');
                }
              }}
            />
            <Input
              label='岗位'
              name='position'
              value={editingEmployee?.position || ''}
              onChange={(e) =>
                setEditingEmployee((prev) => ({
                  ...prev!,
                  nick_name: e.target.value
                }))
              }
            />
            <Input
              label='权限列表'
              name='permissions'
              value={editingEmployee?.permissions || ''}
              onChange={(e) =>
                setEditingEmployee((prev) => ({
                  ...prev!,
                  nick_name: e.target.value
                }))
              }
            />
            <Input
              label='账号状态'
              name='registered'
              value={editingEmployee?.registered || ''}
              options={[
                { label: '已激活', value: 'active' },
                { label: '未激活', value: 'inactive' },
                { label: '已禁用', value: 'disabled' }
              ]}
              onChange={(e) =>
                setEditingEmployee((prev) => ({
                  ...prev!,
                  nick_name: e.target.value
                }))
              }
            />
          </div>
        </Form>
      </EmployeeModal>


      {/* 删除确认弹窗 */}
      <ConfirmModal
        visible={isDeleting}
        title={`确认删除"${deletingEmployee?.nick_name}"，删除成员后，只删除该成员信息。该成员创建的订单仍将保留，是否继续删除？`}
        onConfirm={confirmDelete}
        onCancel={() => {
          setIsDeleting(false);
          setDeletingEmployee(null);
        }}
        content={''}
      />
    </div>
  );
};

export default EmployeeManage;
// export default memo(() => <div>员工列表-待开发</div>);
